export const format4backend = obj => {
  let pairs = []

  const handleStringAndNumber = key => {
    pairs.push(`${key}=${String(obj[key])}`)
  }

  const handleArray = key => {
    if(Array.isArray(obj[key][0])) {
      obj[key].forEach((x, i) => {
        x.forEach((y, j) => {
          for(let subKey of Object.keys(y)) {
            pairs.push(`${key}[${i}][${j}].${subKey}=${y[subKey]}`)
          }
        })
      })
      return
    }
    obj[key].forEach((o, index) => {
      if(o == null) return
      for(let name of Object.keys(o)) {
        pairs.push(`${key}[${index}].${name}=${o[name]}`)
      }
    })
  }

  const handleObj = key => {
    for(let subKey of Object.keys(obj[key])) {
      pairs.push(`${key}.${subKey}=${obj[key][subKey]}`)
    }
  }

  for(let key of Object.keys(obj)) {
    switch(true) {
      case typeof obj[key] === "string" || typeof obj[key] === "number":
        handleStringAndNumber(key)
        break
      case Array.isArray(obj[key]):
        handleArray(key)
        break
      case typeof obj[key] === "object":
        handleObj(key)
        break
      case typeof obj[key] === "undefined":
        break
      default:
        throw new Error("utils:obj2Params can't handle key type: " + key)
    }
  }

  return pairs.join("&")
}

export class FormValidator {
  constructor() {
    this.validators = []
  }

  validate() {
    const ret = this.validators.find(v => v.validator(v.value))
    if(ret) return ret.errorMsg
    return false
  }

  add(value, validator, errorMsg) {
    const funcValidator =
      typeof validator === "string" ? this[validator] : validator
    this.validators.push({
      value,
      validator: funcValidator,
      errorMsg,
    })
  }

  isEmpty(value) {
    return value == null || value === ""
  }
}
